<?php
/**
 * 结算系统运营后台控制器
 *
 */
class Controller_Admin_Bill extends Controller_Template
{
	public function __construct ($req, $res)
	{
		parent::__construct ($req, $res);
		$this->template  = 'smarty:bill/admin/welcome';
		$this->_bill     = new Bill_Info();
		$this->_ratio    = new Bill_Ratio();
		$this->contract  = new Bill_Contract_Info();
		$this->ratios	 = new Bill_Ratio();	
		$this->_limit    = 20;
	}

	public function action_index()
	{
		$this->action_service_fee();
	}

	/**
	 * 合同列表
	 *
	 */
	public function action_contract($order = null)
	{
		$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
		
		$offset = ($page - 1) * $this->_limit;
		
		if(empty($order))
			$order = 'create_time';
		$rs	  = $this->contract->get_contracts($condition, $offset, $this->_limit, $order);
		
		$ratios = new Bill_Ratio();
		if(!empty($rs))
		{
			foreach($rs as $key => $val)
			{
				$rs[$key]['start_time'] = date('Y-m-d', $val['start_time']);
				$rs[$key]['end_time']   = date('Y-m-d', $val['end_time']);
				$rs[$key]['merchant_name'] = Shop::name($val['shop_id']);

				$merchant_uid = $val['merchant_uid'];
				$account = new User_Merchant_Account_Money($merchant_uid);
				$end_time = strtotime(date('Y-m-d', $val['end_time']).' 23:59:59');
				$uid_ratios = $ratios->merchant_ratios($merchant_uid,  $val['start_time'], $end_time);
				if(!empty($uid_ratios))
				{
					foreach($uid_ratios as $k => $v)
					{
						$v['start_time']  = date('Y-m-d', $v['start_time']);
						$v['end_time']    = date('Y-m-d', $v['end_time']);
						$rs[$key]['ratio'][] = $v; 	
					}
				}
			}
		}
		
		$rs_count = $this->contract->get_contracts($condition, 0, 10000, $order);

		$count	= count($rs_count);
		
		$page_config	= array(
							'total_items'	=> $count,
							'items_per_page'=> $this->_limit,
							);
		$pagination		= Pagination::factory($page_config);
		
		$this->template->set('pagination', $pagination->render());
		$this->template->set_filename('smarty:bill/admin/contract');
		$this->template->set('data', $rs);
		$this->template->set('count', $count);
		$this->template->set('page_title', '合同列表');
		$this->template->set('navigation_menu', 'contract');
		$this->response->body($this->template->render());
	}

	/**
	 * 获得某商户的合同列表
	 *
	 */
	public function action_get_contract()
	{
		$merchant_uid = $this->request->post("merchant_uid");
	
		if(empty($merchant_uid))
			$merchant_uid = $uid;
		
		$condition['merchant_uid'] = (int) $merchant_uid;

		$rs	  = $this->contract->get_contracts($condition, 0, 100);
	
		$str  = '';
		if(!empty($rs))
		{
			foreach($rs as $key => $val)
			{
				$rs[$key]['start_time'] = date('Y-m-d', $val['start_time']);
				$rs[$key]['end_time']   = date('Y-m-d', $val['end_time']);
				if($key == 0)
					$checked = 'checked="true"';
				else
					$checked = '';
				$str .= '<input type="radio" '.$checked.' onchange="show_fee_annual();" id="contract_id" name="contract_id" value="'.$val['id'].'" />'.' 合同号 ：<a href=/bill/contract_detail/'.$val['id'].'>' . $val['number'] . '</a>  有效期： '.$rs[$key]['start_time']. ' - '. $rs[$key]['end_time'].'<input type="text" style="display:none;" id="contract_fee_annual_'.$val['id'].'" value="'.($val['annual_fee']/100 ).'"/>' .'<input type="text" style="display:none;" id="contract_margin_'.$val['id'].'" value="'.($val['margin']/100 ).'"/>'. '<input type="text" style="display:none;" id="contract_stored_service_'.$val['id'].'" value="'.($val['stored_service']/100 ).'"/>' .'<br/>';
			}
		}
		echo $str;
		exit;	
	}

	/**
	 * 添加合同
	 */
	public function action_addcontract()
	{
		$shops = Model_Shopinfo::shop_lists($condition, 0, 10000);	
		$params = $this->request->post();
	
		if($params['action'] == 'add')
		{
			$data = $this->get_contract_params();	
			$has_contract  = $this->contract->has_contract_number($data['number']);
			
			if(!$has_contract && $data['start_time'] > 0 && $data['end_time'] > 0)
			{
				if(!empty($data))
					$contract_id = $this->contract->insert_contract($data);
			
				if($contract_id > 0)
				{
					$uid		= (int) $data['merchant_uid'];
				
					$ratio_start_time = strtotime($params['ratio_start_time']);

					$ratio_end_time   = strtotime($params['ratio_end_time']);

					$start_time = ($ratio_start_time > 0 && $ratio_start_time >= $data['start_time']) ? strtotime($params['ratio_start_time']) : $data['start_time'];
					
					$end_time	= ($ratio_end_time > 0 && $ratio_end_time <= $data['end_time']) ? strtotime($params['ratio_end_time']) : $data['end_time'];
					
					$ratio		= (int) $params['ratio'];
					
					$obj		= new Bill_Ratio();
					
					$rs			= $obj->set_merchant_ratio($uid, $start_time, $end_time, $ratio, $contract_id);
					echo '<script>alert("添加成功!");window.location.href="/bill/contract_detail/'.$contract_id.'";</script>';

				}else{
					$msg		= '添加失败！ 合同有效期间不能重叠或者合同号重复.';
				}
			}else
				$msg = '此合同号已经存在或者合同有效期填写错误！';
		}
		$name = User::current_user_name();

		$this->template->set_filename('smarty:bill/admin/contract-add');
		$this->template->set('page_title', '添加合同');
		$this->template->set('current_name', $name);
		$this->template->set('shops', $shops);
		$this->template->set('message', $msg);
		$this->template->set('navigation_menu', 'contract');
		$this->response->body($this->template->render());
	}

	/**
	 * 更新详情
	 *
	 */
	public function action_contract_detail($id)
	{
		$id   = (int) $id;
		
		$info = $this->get_info($id);	
		
		$uid_ratios = $this->ratios->merchant_ratios($info['merchant_uid'],  strtotime($info['start_time']), strtotime($info['end_time'].' 23:59:59'));
		if(!empty($uid_ratios))
		{
			foreach($uid_ratios as $k => $v)
			{
				$v['start_time']  = date('Y-m-d', $v['start_time']);
				$v['end_time']    = date('Y-m-d', $v['end_time']);
				$ratios[] = $v; 	
			}
		}
 		$modify_list           = Bill_Log_Contract::get_log_modify($id);
		$act_money = new User_Merchant_Account_Money($info['merchant_uid']);
		$money_list= $act_money->get_money_list_detail(strtotime($info['start_time']), strtotime($info['end_time'].' 23:59:59'), array($info['merchant_uid']), 'stored_service');
		
		$this->template->set_filename('smarty:bill/admin/contract-detail');
		$this->template->set('info', $info);
		$this->template->set('ratios', $ratios);
		$this->template->set('message', '');
 		$this->template->set('modify_list', $modify_list);
		$this->template->set('money_list', $money_list);
		$this->template->set('page_title', '合同详情');
		$this->template->set('navigation_menu', 'contract');
		$this->response->body($this->template->render());
	}

	/**
	 * 判断合同是否存在 
	 *
	 */
	public function action_has_contract()
	{
		$number = trim($this->request->post("number"));
	
		if(empty($number))	
		{
			echo '参数错误！';
			exit;
		}

		$rs	  = $this->contract->has_contract_number($number);

		echo $rs;
		
		exit;
	}


	protected function check_time($data)
	{
		$id	= $data['contract_id'];
	
		$rs	= $this->contract->get_contract_by_id($id);

		if($data['start_time'] >= $rs['start_time'] && $data['end_time'] <= $rs['end_time'])
		{
			$account   = new User_Merchant_Account($data['merchant_uid']);
			//是否充过
			$rs = $account->has_account_info($data['merchant_uid'], $data['start_time'], $data['end_time']);
			
			if($rs)
				return '充值失败，年费的缴费期不能重复！';
			else
				return 'TRUE';
		}else{
			return $message = '充值失败，您选择的年费有效期不再合同有效期范围内，请重新输入！';		
		}
	}

	/**
	 * 给商家账户充值
	 *
	 */
	public function action_add($merchant_uid = null)
	{
		$data	= $this->get_params();
		$account = new User_Merchant_Account($data['merchant_uid']);

		if(!empty($data))
		{
			//年费判断有效期与合同的有效期是否匹配
			if($data['recharge_type'] == 'annual_fee' && $data['contract_id'] > 0)
			{
				$rs = $this->contract->get_contract_by_id($data['contract_id']);
			    $data['start_time'] = $rs['start_time'];
			    $data['end_time']   = $rs['end_time'];
				$check_rs = $this->check_time($data);
			}
			$has_margin = false;
			//保证金
			if($data['recharge_type'] == 'margin')
			{
				$has_margin = $account->contract_margin_status($data['contract_id']);
			}
			$merchant_contract = $this->contract->get_contract($data['merchant_uid']);
			if(!empty($merchant_contract) && !$has_margin)	
			{
				if($data['recharge_type'] != 'annual_fee' || ($data['recharge_type'] == 'annual_fee' && $check_rs == 'TRUE') || $data['contract_id'] == 0 )
				{
					$rs	= $account->recharge_account_money($data['recharge_type'], $data['money'], $data);
			
					$merchant_uid	= $data['merchant_uid'];
					if($rs)
						$msg = '充值成功！';
					else
						$msg = '充值失败！';
				}else
					$msg = $check_rs;
			}
			else
			{
				if($has_margin)
					$msg = '充值失败， 一个合同只能充一次保证金！';
				else
					$msg = '该商家无合同信息， 请先录入合同信息！';
			}
		}
		$shops = Model_Shopinfo::shop_lists($condition, 0, 10000);
		$name = User::current_user_name();

		$this->template->set('message', $msg);
		$this->template->set('type', 'add');
		$this->template->set('merchant_uid', $merchant_uid);
		$this->template->set('user_name', $name);
		$this->template->set('shops', $shops);
		$this->template->set('page_title', '充值');
		$this->template->set('navigation_menu', 'receipt');
		$this->template->set_filename('smarty:bill/admin/proceeds-set');
		$this->response->body($this->template->render());
	}

	/**
	 *  修改收款
	 *
	 */
	public function action_updatemoney($id = null)
	{
		$id   = (int) $id;
		
		$params = $this->request->post();
		
		if($params['action'] == 'update')
		{
			$id                      = (int) $params['fee_id'];
			$data['invoice_time']    = strtotime($params['invoice_date']);
			$data['invoice_status']  = (int) $params['invoice_status'];
			$data['desc']		     = strval($params['desc']);
			$data['operate_desc']    = strval($params['operate_desc']);
			$data['operater_man']    = strval($params['operater_man']);
				
			$account   = new User_Merchant_Account($data['merchant_uid']);
			if(!empty($data))
			{
				if($account->set_account_info($id, $data))
				{
					echo '<script>alert("修改成功!");window.location.href="/bill/money_detail/'.$id.'";</script>';
					//$msg = '修改成功！';
				}else
					$msg = '修改失败！';
			}
		}
		$account = new User_Merchant_Account($id);
		$info = $account->account_one_info($id);
		$info['merchant_name'] = Shop::name($info['shop_id']);
 		$modify_list           = Bill_Log_Charge::get_log_modify($id);
		$this->template->set_filename('smarty:bill/admin/proceeds-update');
 		$this->template->set('modify_list', $modify_list);
		$this->template->set('info', $info);
		$this->template->set('message', $msg);
		$this->template->set('page_title', '修改费用');
		$this->template->set('navigation_menu', 'receipt');
		$this->response->body($this->template->render());
	}
	
	/**
	 *  收款详情
	 *
	 */
	public function action_money_detail($id)
	{
		$id   = (int) $id;
		
		$account = new User_Merchant_Account($id);
		$info = $account->account_one_info($id);
		$info['merchant_name'] = Shop::name($info['shop_id']);
 		$modify_list           = Bill_Log_Charge::get_log_modify($id);
		$this->template->set_filename('smarty:bill/admin/money-detail');
 		$this->template->set('modify_list', $modify_list);
		$this->template->set('info', $info);
		$this->template->set('message', '修改成功');
		$this->template->set('page_title', '收款详情');
		$this->template->set('navigation_menu', 'receipt');
		$this->response->body($this->template->render());
	}

	/**
	 * 更新合同
	 *
	 */
	public function action_update($id = 0)
	{
		$id   = (int) $id;
		$params = $this->request->post();
		
		if($params['action'] == 'update')
		{
			$data = $this->get_update_contract_params();	
			$rs	  = $this->contract->has_contract_number($data['number'], $params['id']);
			$u_ma = new User_Merchant_Account($params['merchant_uid']);
			
			if(!$rs){
				
				$contract_status = $u_ma->contract_pay_status($params['id']);

				if(!empty($data) && $contract_status['pay_status'] == $data['flag'])
				{
					$this->contract->update_contract($params['id'], $data);
					
					echo '<script>alert("修改成功!");window.location.href="/bill/contract_detail/'.$params['id'].'";</script>';

				}else{
					if($contract_status['pay_status'] != $data['flag']){
						$msg = '目前此合同的支付状态是 "'.$contract_status['pay_status_name'].'" ';
					}else
						$msg = '修改失败！';
				}
			}else{
				$msg = '修改失败，合同号重复。';
			}
			$id = $params['id'];
		}
		$shops = Model_Shopinfo::shop_lists($condition, 0, 10000);
		$info = $this->get_info($id);	
		
		$uid_ratios = $this->ratios->merchant_ratios($info['merchant_uid'],  strtotime($info['start_time']), strtotime($info['end_time'].' 23:59:59'));
		if(!empty($uid_ratios))
		{
			foreach($uid_ratios as $k => $v)
			{
				$v['start_time']  = date('Y-m-d', $v['start_time']);
				$v['end_time']    = date('Y-m-d', $v['end_time']);
				$ratios[] = $v; 	
			}
		}
 		$modify_list           = Bill_Log_Contract::get_log_modify($id);
		$act_money = new User_Merchant_Account_Money($info['merchant_uid']);
		$money_list= $act_money->get_money_list_detail(strtotime($info['start_time']), strtotime($info['end_time'].' 23:59:59'), array($info['merchant_uid']), 'stored_service');
		$this->template->set_filename('smarty:bill/admin/contract-update');
		$this->template->set('info', $info);
		$this->template->set('message', $msg);
		$this->template->set('shops', $shops);
		$this->template->set('ratios', $ratios);
 		$this->template->set('modify_list', $modify_list);
		$this->template->set('money_list', $money_list);
		$this->template->set('page_title', '修改合同');
		$this->template->set('navigation_menu', 'contract');
		$this->response->body($this->template->render());
	}

	private function get_info($id)
	{
		$rs	= $this->contract->get_contract_by_id($id);

		if(!empty($rs))
		{
			$act_money = new User_Merchant_Account_Money($uid);
			$rs['is_haved_annual_fee'] = $act_money->is_haved_annual_fee($id);
			$rs['is_haved_margin']     = $act_money->is_haved_margin($id);
			$rs['is_haved_service']    = $act_money->is_haved_stored_service($id);
			$rs['merchant_name']       = Shop::name($rs['shop_id']);
			$rs['start_time']	       = date('Y-m-d', $rs['start_time']);
			$rs['end_time']            = date('Y-m-d', $rs['end_time']);
			$rs['annual_fee']          = floatval($rs['annual_fee']/100) ;
			$rs['technical_service']   = floatval($rs['technical_service']/100) ;
			$rs['margin']		       = floatval($rs['margin']/100);
			$rs['stored_service']      = floatval($rs['stored_service']/100);
		}

		return $rs;
	}

	private function get_update_contract_params()
	{
		$params = $this->request->post();
		$uid    = $params['merchant_uid'];
		$obj_shop  = new Model_Shopinfo();
		$shop_info = $obj_shop->get_shopinfo_byuid($uid);
		
		$data['number']			= strval(trim($params['contract_number']));
		$data['status']			= strval($params['contract_status']);
		$data['flag']			= strval($params['pay_status']);
		$data['description']	= strval($params['description']);
		if(isset($params['margin']))
			$data['margin']	        = (int) $params['margin'] * 100;
		if(isset($params['stored_service']))
			$data['stored_service'] = (int) $params['stored_service'] * 100;
		if(isset($params['annual_fee']))
			$data['annual_fee']     = (int) $params['annual_fee'] * 100;
		
		return $data;
	}

	private function get_contract_params()
	{
		$params = $this->request->post();
		$uid    = $params['merchant_uid'];
		$obj_shop  = new Model_Shopinfo();
		$shop_info = $obj_shop->get_shopinfo_byuid($uid);
		
		$data['merchant_uid']	= (int) $params['merchant_uid'];
		$data['shop_id']		= (int) $shop_info[0]['id']; 
		$data['number']			= strval($params['contract_number']);
		$data['annual_fee']		= $params['annual_fee']*100;
		$data['stored_service'] = $params['stored_service']*100;
		$data['technical_service']  = $params['technical_service']*100;
		$data['margin']			= $params['margin']*100;
		$data['start_time']		= strtotime($params['start_time']);
		$data['end_time']		= strtotime($params['end_time']);	
		$data['man']			= strval($params['contract_man']);
		$data['status']			= strval($params['contract_status']);
		$data['flag']			= strval($params['pay_status']);
		$data['pay_man']		= strval($params['pay_man']);
		$data['description']	= strval($params['description']);
		
		return $data;
	}


	/**
	 *	服务费页面
	 */
	public function action_service_fee($year = NULL)
	{
		if (empty($year))
			$year = date('Y');
		$amount = $this->get_amount($year);
		$this->template->set('year',$year);
		$this->template->set('amount',$amount);
		$this->template->set('page_title','服务费');
		$this->template->set('navigation_menu', 'service_charge');
		$this->template->set_filename('smarty:bill/admin/service-charge');
	}

	/**
	 * 以月为单位充值列表 统计概况
	 */
	public function action_fee_list($year = NULL)
	{
		$y         = empty($year) ? date('Y',time()) : $year;
		$before_y  =	$y - 1; 
		$next_y    =	$y + 1; 
		$list      = array();
		$uid       = User::current_user_id();

		$act_money = new User_Merchant_Account_Money($uid);
		$lists     = $act_money->get_money_list($y);
		$list      = $lists['list'];
		$sum       = $lists['sum'];

		$this->template->set('year',$y);
		$this->template->set('before_year',$before_y);
		$this->template->set('next_year',$next_y);
		$this->template->set('list',$list);
		$this->template->set('sum',$sum);
		$this->template->set('page_title', '结算系统-缴费列表');
		$this->template->set('navigation_menu', 'receipt');
		$this->template->set_filename('smarty:bill/admin/proceeds');
	}

	/**
	 * 月充值列表 - 详细
	 */
	public function action_fee_list_detail($month = NULL)
	{
		$merchant_uids   = array();
		$is_invoice      = -1;
		$m               = empty($month) ? date('Y-m',time()) : $month;
		$start_time      = strtotime($m.'-01');
		$end_time        = strtotime("+1month",$start_time) - 1;
		$query           = $this->request->query();
		$shops           = Model_Shopinfo::shop_lists(array(), 0, 10000);
		if(!empty($shops))
		{
			foreach($shops as $sp)
			{
				$uids[] = $sp['uid'];
			}
		}

		if(!empty($query))
		{
			$merchant_uid  = Arr::get($query, 'merchant_uid', 0);
			$start_time    = $this->request->query('start_time');
			$start_time    = empty($start_time) ? (time() - 86400*90) : strtotime($start_time);
			$end_time      = $this->request->query('end_time');
			$end_time      = empty($end_time) ? time() : strtotime($end_time)+86400-1;
			$charge_type   = Arr::get($query, 'charge_type',0);
			$is_invoice    = Arr::get($query, 'is_invoice', -1); 

			if($merchant_uid == 0)
				$merchant_uids = $uids;
			else
				$merchant_uids[] = $merchant_uid;
		}

		$act_money = new User_Merchant_Account_Money($uid);
		$list      = $act_money->get_money_list_detail($start_time, $end_time, $merchant_uids, $charge_type, $is_invoice);

		$this->template->set('month',$m);
		$this->template->set('list',$list);
		$this->template->set('shops', $shops);
		$this->template->set('merchant_uid', $merchant_uid);
		$this->template->set('start_time', date('Y-m-d',$start_time));
		$this->template->set('end_time', date('Y-m-d',$end_time));
		$this->template->set('charge_type', $charge_type);
		$this->template->set('is_invoice', $is_invoice);
		$this->template->set('page_title', '结算系统-缴费列表');
		$this->template->set('navigation_menu', 'receipt');
		$this->template->set_filename('smarty:bill/admin/proceeds-detail');
	}

	protected function get_merchant_contract($uid)
	{
		if(intval($uid) > 0)
			$merchant_uid = $uid;
		else
			return '';

		$condition['merchant_uid'] = (int) $merchant_uid;
		
		$rs	  = $this->contract->get_contracts($condition, 0, 100);
	
		$str  = '';
		if(!empty($rs))
		{
			foreach($rs as $key => $val)
			{
				$rs[$key]['start_time'] = date('Y-m-d', $val['start_time']);
				$rs[$key]['end_time']   = date('Y-m-d', $val['end_time']);
				if($key == 0)
					$checked = 'checked="true"';
				else
					$checked = '';
				$str .= '<input type="radio" '.$checked.' id="contract_id" name="contract_id" value="'.$val['id'].'" />'.' 合同号 ：<a href="/bill/contract_detail/'.$val['id'].'" target=_blank>'.$val['number'] . '</a>  有效期： '.$rs[$key]['start_time']. ' - '. $rs[$key]['end_time'].'<br/>';
			}
		}
		return $str;
	}
	
	/**
	 * 收款的修改记录
	 */
	public function action_charge_modify_log($id = NULL)
	{
		$id               = empty($id) ? 0 : (int) $id;
		$modify_list      = Bill_Log_Charge::get_log_modify($id);
		$this->template->set('modify_list', $modify_list);
		$this->template->set('page_title', '结算系统-收款日志列表');
		$this->template->set('navigation_menu', 'receipt');
		$this->template->set_filename('smarty:bill/admin/charge-log-list');
	}
	
	/**
	 * 合同的修改记录
	 */
	public function action_contract_modify_log($id = NULL)
	{
		$id               = empty($id) ? 0 : (int) $id;
		$modify_list      = Bill_Log_Contract::get_log_modify($id);
		$this->template->set('modify_list', $modify_list);
		$this->template->set('page_title', '结算系统-合同修改记录');
		$this->template->set('navigation_menu', 'contract');
		$this->template->set_filename('smarty:bill/admin/contract-log-list');
	}

	/**
	 * 添加费率
	 *
	 */
	public function action_addratio($merchant_uid = 0)
	{
		$param = $this->request->post();
		$shops = Model_Shopinfo::shop_lists($condition, 0, 10000);	
		$obj   = new Bill_Ratio();
		if($param['action'] == 'add')
		{
			$uid = (int) $param['merchant_uid'];
			$start_time = strtotime($param['start_time']);
			$end_time	= strtotime($param['end_time']);
			$contract_id= intval($param['contract_id']);
			$ratio		= (int) $param['ratio'];
			if($ratio >= 0 && $ratio <100 && is_numeric($param['ratio']))
			{
				$rs	= $this->contract->get_contract_by_id($contract_id);
				
				if(!empty($rs))
				{
					if($start_time >= $rs['start_time'] && $end_time <= $rs['end_time'])
					{
						$rs = $obj->set_merchant_ratio($uid, $start_time, $end_time, $ratio, $contract_id);
						if($rs)
							$msg = '添加成功！';
						else
							$msg = '添加失败！ 费率的有效区间不能有重叠。';
					}else{
						$msg = '费率有效期不在合同有效期范围内，请重新输入！';		
					}	
				}else{
					$rs = $obj->set_merchant_ratio($uid, $start_time, $end_time, $ratio);
					if($rs)
						$msg = '添加成功！';
					else
						$msg = '添加失败！ 费率的有效区间不能有重叠。';
				}
				$merchant_uid = $uid;
			}else
				echo '<script>alert("费率要大于0 小于100！");window.location.href="/bill/addratio/'.$uid.'";</script>';
		}
		$contract_html = $this->get_merchant_contract($merchant_uid);
		$uid_ratios	   = $this->ratios->merchant_ratios($merchant_uid);
		if(!empty($uid_ratios))
		{
			foreach($uid_ratios as $k => $v)
			{
				$v['start_time']  = date('Y-m-d', $v['start_time']);
				$v['end_time']    = date('Y-m-d', $v['end_time']);
				$rs_ratios[] = $v; 	
			}
		}
		$obj_shop  = new Model_Shopinfo();
		$shop_info = $obj_shop->get_shopinfo_byuid($merchant_uid);
		$this->template->set_filename('smarty:bill/admin/fee-add');
		$this->template->set('page_title', '费率添加');
		$this->template->set('shops', $shops);
		$this->template->set('contract_info', $contract_html);
		$this->template->set('message', $msg);
		$this->template->set('ratios', $rs_ratios);
		$this->template->set('shop_info', $shop_info);
		$this->template->set('merchant_uid', $merchant_uid);
		$this->template->set('navigation_menu', 'contract');
		$this->response->body($this->template->render());
	}

	/*
	 * 修改费率
	 *
	 */
	public function action_ratio()
	{
		$param = $this->request->post();

		$rateId = $param['rateId'];
		
		$ratio	= (int) $param['rate'];
		
		$merchant_uid = (int) $param['m_uid'];

		$obj	= new Bill_Ratio();
		
		if($ratio >= 0 && $ratio < 100 && is_numeric($param['rate']))	
		{
			$rs		= $obj->update_merchant_ratio($rateId, $ratio, $merchant_uid);
			$url	= '/bill/contract';;
			$this->request->redirect($url, $code = 302);
		}else
			echo '<script>alert("费率要大于0 小于100！");window.location.href="/bill/contract";</script>';

		
	}

	public function action_delratio()
	{
		$param = $this->request->post();

		$ratio_id = intval($param['ratio_id']);
		$uid	  = intval($param['merchant_uid']);

		if($ratio_id <= 0)
			return false;

		$obj    = new Bill_Ratio();
		
		$rs	 = $obj->del_one_ratio($ratio_id, $uid);	
		
		if($rs)
			echo '删除成功！';
		else
			echo '删除失败！';
	}

	private function get_params()
	{
		$params = $this->request->post();

		$data	= array();

		if($params['action'] == 'add')
		{
			$data['merchant_uid']	= (int) $params['merchant_uid'];
			$data['recharge_type'] = strval($params['recharge_type']);
			$data['money']		   = (int) ($params['money'] * 100);
			$data['status']		   = 1;
			$data['start_time']    = strtotime($params['start_time']);
			$data['end_time']	   = strtotime($params['end_time']);
			$data['contract_id']   = (int) $params['contract_id'];
			$data['invoice']	   = strtotime($params['invoice_date']);
			$data['invoice_status']= (int) $params['invoice_status'];
			$data['desc']		   = strval($params['desc']);
			$data['operate_desc']  = strval($params['operate_desc']);
			$data['operate_man']   = strval($params['operate_man']);
		}

		return $data;
	}

	/**
	 *  未出账单列表
	 */
	public function action_unfinished_bill()
	{
		$shop_id = $this->request->query('shop_id');
		$condition = array(
			'status' => 'draft',
		);
		if ($shop_id > 0)
		{
			$condition['shop_id'] = $shop_id;
			// 获取商家服务费余额
			$service_fee = $this->_bill->shop_service_fee($shop_id);
			// 获取商家未出交易额与服务费
			$shop_unfinished_amount = $this->_bill->get_unfinished_order_amount($shop_id);
		}
		else
		{
			$service_fee = 0;
			$shop_unfinished_amount = array(
				'amount_real'    => 0,
				'amount_service' => 0,
			);
		}

		$page = $this->request->query('page');
		$page = $page > 0 ? $page : 1;
		$limit = Kohana::config('bill.perpage');
		$offset = intval(($page - 1) * $limit);
		$offset = $offset > 0 ? $offset : 0;
		$order_by = array('order_pay_time' => 'ASC');

		$bill_list = $this->_bill->get_bill_list($condition,$limit,$offset,$order_by);
		$bill_count = $this->_bill->get_bill_count($condition);
		
		$shops           = Model_Shopinfo::shop_lists(array('open_status'=>1), 0, 10000);
		
		//分页相关设置
		$page_config = array(
	        'total_items'       => $bill_count,
	        'items_per_page'    => $limit,
			'current_page'      => array('source' => 'query_string', 'key' => 'page'),
		);
		//编译分页
	    $pagination = Pagination::factory($page_config);
	    $total_page = intval($pagination->total_pages);
		$this->template->set('total_page',$total_page);
		$this->template->set('pagination', $pagination->render());
		$this->template->set('bill_list',$bill_list);
		$this->template->set('count',$bill_count);
		$this->template->set('shop_service_fee',$service_fee);
		$this->template->set('shop_unfinished_amount',$shop_unfinished_amount);
		$this->template->set('shops',$shops);
		$this->template->set('shop_id',$shop_id);
		$this->template->set('page_title', '未出账单');
		$this->template->set_filename('smarty:bill/admin/unfinished_bill');
	}

	/**
	 *	账单概况页面
	 */
	public function action_profile()
	{
		$month = $this->request->query('month');
		$status = $this->request->query('status');
		$shop_name = $this->request->query('shop_name');
		$start_date = $this->request->query('start_date');
		$end_date   = $this->request->query('end_date');
		$condition = array();
		if (!empty($month))
		{
			$condition['month'] = $month;
			$start_date = date('Y-m-d',strtotime($month));
			$end_date = date('Y-m-d',strtotime('+1 month',strtotime($month)));
		}
		if ($status == 'merchant_unconfirm')
			$condition['merchant_confirm'] = 'undeal';
		if ($status == 'no_receipt')
			$condition['receipt_status'] = 'undeal';
		if ($status == 'need_receipt')
		{
			$condition['merchant_confirm'] = 'confirm';
			$condition['receipt_status']   = 'undeal';
		}
		if (!empty($shop_name))
		{
			$passport	= strval($this->request->query('shop_name'));
			$condition['passport']	= $passport;
			$data			= Model_Shopinfo::shop_lists($condition,0,1);
			if (!empty($data))
			{
				$shop_info = current($data);
				$shop_id = Arr::get($shop_info,'id',NULL);
				$condition['shop_id'] = $shop_id;
			}	
		}
		if (!empty($start_date) && empty($month))
			$condition['start_time'] = strtotime($start_date);
		if (!empty($end_date) && empty($month))
			$condition['end_time']   = strtotime($end_date);
			
		$page = $this->request->query('page');
		$page = $page > 0 ? $page : 1;
		$limit = Kohana::config('bill.page_limit.admin.profile');
		$offset = intval(($page - 1) * $limit);
		$offset = $offset > 0 ? $offset : 0;
		$order_by = array('amount_service' => 'DESC');
			
		$profile_list = $this->_bill->get_profile_list($condition,$limit,$offset,$order_by);
		$profile_count = $this->_bill->get_profile_count($condition);
		
		//分页相关设置
		$page_config = array(
	        'total_items'       => $profile_count,
	        'items_per_page'    => $limit,
			'current_page'      => array('source' => 'query_string', 'key' => 'page'),
	    );
		$shops           = Model_Shopinfo::shop_lists(array('open_status'=>1), 0, 10000);

		//编译分页
	    $pagination = Pagination::factory($page_config);
	    $total_page = intval($pagination->total_pages);
		$this->template->set('total_page',$total_page);
		$this->template->set('pagination', $pagination->render());
		$this->template->set('profile_list',$profile_list);
		$this->template->set('month',$month);
		$this->template->set('status',$status);
		$this->template->set('shops',$shops);
		$this->template->set('shop_name',$shop_name);
		$this->template->set('start_date',$start_date);
		$this->template->set('end_date',$end_date);
		$this->template->set('count',$profile_count);
		$this->template->set('page_title', '账单概况');
		$this->template->set('navigation_menu', 'service_charge');
		$this->template->set_filename('smarty:bill/admin/service-charge-detail');
	}
	
	/**
	 *	账单详情页面（订单列表）
	 */
	public function action_list($shop_id,$month)
	{
		$ratio = 0;
		
		//计算月开始与结束时间
		$start_time = strtotime($month);
		$t = date("t",$start_time);
		$end_time = $start_time + ($t * 24 * 3600) - 1;
		$condition = array(
			'shop_id' => $shop_id,
			'status'  => 'finished',
			'start_time' => $start_time,
			'end_time'   => $end_time,
		);

		$shop_info = Shop::shop_info($shop_id);
		$merchant_uid = Arr::get($shop_info,'uid',0);
		$shop_name    = Arr::get($shop_info,'shop_short_name',NULL); 
		
		$page = $this->request->query('page');
		$page = $page > 0 ? $page : 1;
		$limit = Kohana::config('bill.page_limit.admin.list');
		$offset = intval(($page - 1) * $limit);
		$offset = $offset > 0 ? $offset : 0;
		
		$bill_list = $this->_bill->get_bill_list($condition,$limit,$offset);
		$bill_count = $this->_bill->get_bill_count($condition);
		$profile   = $this->_bill->get_profile_detail($shop_id,$month);
		if ($merchant_uid > 0 && isset($profile['start_time']) && isset($profile['end_time']))
		{
			$ratio_time = ($profile['start_time'] + $profile['end_time']) / 2;
			$ratio = $this->_ratio->merchant_ratio($merchant_uid,$ratio_time);
		}
		else
		{
			$ratio = 0;
		}
		
		//分页相关设置
		$page_config = array(
	        'total_items'       => $bill_count,
	        'items_per_page'    => $limit,
			'current_page'      => array('source' => 'query_string', 'key' => 'page'),
	    );

		//编译分页
	    $pagination = Pagination::factory($page_config);
	    $total_page = intval($pagination->total_pages);
		$this->template->set('total_page',$total_page);
		$this->template->set('pagination', $pagination->render());
		$this->template->set('bill_list',$bill_list);
		$this->template->set('count',$bill_count);
		$this->template->set('profile',$profile);
		$this->template->set('ratio',$ratio);
		$this->template->set('shop_name',$shop_name);
		$this->template->set('page_title', '账单详情列表');
		$this->template->set('navigation_menu', 'service_charge');
		$this->template->set_filename('smarty:bill/admin/service-charge-detail-one-merchant');
	}
	
	/**
	 *	设置备注
	 */
	public function action_set_tips()
	{
		$shop_id = $this->request->post('shop_id');
		$month   = $this->request->post('month');
		$tips    = $this->request->post('tips');
		$mall_tips = $this->request->post('mall_tips');
		$return_url = $this->request->post('return_url');
		$status = array(
			'tips' => $tips,
			'mall_tips' => $mall_tips,
		);
		$this->_bill->set_profile_status($shop_id,$month,$status);
		
		$default_url = '/bill/profile';
		
		if (!empty($return_url))
			$this->request->redirect($return_url);
		else 
			$this->request->redirect($default_url);
	}
	
	/**
	 *	开发票
	 */
	public function action_invoice($shop_id,$month)
	{
		if (empty($shop_id) || empty($month))
			$this->request->redirect('/bill/profile');
		$profile   = $this->_bill->get_profile_detail($shop_id,$month);
		
		$receipt_status = $this->request->post('receipt_status');
		$invoice_date = $this->request->post('invoice_date');
		$tips    = $this->request->post('tips');
		$mall_tips = $this->request->post('mall_tips');
		
		if (!empty($receipt_status))
		{
			if (!empty($invoice_date))
				$receipt_time = strtotime($invoice_date);
			else
				$receipt_time = time();
			$update = array(
				'receipt_status' => $receipt_status,
				'receipt_time'   => $receipt_time,
				'tips' => $invoice_date.' '.$tips,
				'mall_tips' => $mall_tips,
			);
			$this->_bill->set_profile_status($shop_id,$month,$update);
			$this->request->redirect('/bill/profile');
		}
		
		$this->template->set('profile',$profile);
		$this->template->set('page_title','开发票');
		$this->template->set('navigation_menu', 'service_charge');
		$this->template->set_filename('smarty:bill/admin/service-charge-invoice');
	}

    /**
     *导出到CSV文件
     */
    public function action_export()
    {
        $billinf      = $this->get_export_data();
        $list         = $billinf['bill_list'];
        $profile      = $billinf['profile'];
		$ratio        = $billinf['ratio'];
        $current_time = date('Y-m-d H-i',time());
		$file_name = $profile['shop_name'].$profile['month'].'账单.xls';
        $xml = new ExcelWriterXML(mb_convert_encoding($file_name,'gb2312','utf8'));
        $sheet1 = $xml->addSheet('jia.focus.cn_bill_list');

        $format1 = $xml->addStyle('big_title');
        $format1->fontSize(14);
        $format1->fontBold();
        $format1->alignHorizontal('Center');
        $format1->alignVertical('Center');
        $format1->border('All',1,'#ccc');
        $format1->bgColor('#99CC33');
        $format1->fontColor('Black');

        $format5 = $xml->addStyle('lightskyblue');
        $format5->bgColor('LightSkyBlue');
        $format5->border('All',1,'#ccc');
        $format5->alignVertical('Center');
        $format5->fontSize(12);
        $format5->fontColor('Black');

        $format6 = $xml->addStyle('lightgrey');
        $format6->bgColor('LightGrey');
        $format6->border('All',1,'#ccc');
        $format6->alignVertical('Center');
        $format6->fontSize(12);
        $format6->fontColor('Black');

		//第一行横向合并十个
		$sheet1->cellMerge(1,1,9,0);
        $sheet1->writeString(1,1,'时间：'.date('Y-m-d',$profile['start_time']).' 至 '.date('Y-m-d',$profile['end_time']),$format5);

		$sheet1->cellMerge(2,1,9,0);
        $sheet1->writeString(2,1,'服务费：'.$profile['amount_service'],$format5);

		$sheet1->cellMerge(3,1,9,0);
        $sheet1->writeString(3,1,'交易金额：'.$profile['amount_real'],$format5);

		$sheet1->cellMerge(4,1,9,0);
        $sheet1->writeString(4,1,'费率：'.$ratio.'%',$format5);

		$sheet1->cellMerge(5,1,9,0);
        $sheet1->writeString(5,1,'备注：'.$profile['tips'],$format5);

        $sheet1->columnWidth(1,'150');
        $sheet1->columnWidth(2,'300');
        $sheet1->columnWidth(3,'150');
        $sheet1->columnWidth(4,'150');
        $sheet1->columnWidth(5,'90');
        $sheet1->columnWidth(6,'90');
        $sheet1->columnWidth(7,'90');
        $sheet1->columnWidth(8,'150');
        $sheet1->columnWidth(9,'90');
        $sheet1->columnWidth(10,'90');
       
        $sheet1->writeString(6,1,'订单号',$format1);
        $sheet1->writeString(6,2,'商品名称',$format1);
        $sheet1->writeString(6,3,'支付宝交易号',$format1);
        $sheet1->writeString(6,4,'支付时间',$format1);
        $sheet1->writeString(6,5,'交易金额',$format1);
        $sheet1->writeString(6,6,'实际交易金额',$format1);
        $sheet1->writeString(6,7,'交易状态',$format1);
        $sheet1->writeString(6,8,'时间',$format1);
        $sheet1->writeString(6,9,'费率',$format1);
        $sheet1->writeString(6,10,'服务费',$format1);

		$start = 7;
        $order_key = 0;
        foreach($list as $bill)
        {
            $format_row    = $order_key%2==0 ? $format5 : $format6;
            $sheet1->writeString($start,1,$bill['order_id'],$format_row);
            $sheet1->writeString($start,2,$bill['goods_title'],$format_row);
            $sheet1->writeString($start,3,$bill['alipay_id'],$format_row);
            $sheet1->writeString($start,4,$bill['order_pay_time'],$format_row);
            $sheet1->writeString($start,5,$bill['amount_paid'],$format_row);
            $sheet1->writeString($start,6,$bill['amount_real'],$format_row);
            $sheet1->writeString($start,7,$bill['order_status'],$format_row);
            $sheet1->writeString($start,8,$bill['order_end_time'],$format_row);
            $sheet1->writeString($start,9,$bill['ratio'].'%',$format_row);
            $sheet1->writeString($start,10,$bill['amount_service'],$format_row);
            $start++;
        }

        $xml->sendHeaders();
        $xml->writeData();
        exit;
    }

	protected function get_export_data()
	{
		$shop_id = $this->request->query('shop_id');
		$month   = $this->request->query('month');
		
		//计算月开始与结束时间
		$start_time = strtotime($month);
		$t = date("t",$start_time);
		$end_time = $start_time + ($t * 24 * 3600) - 1;
		$condition = array(
			'shop_id' => $shop_id,
			'status'  => 'finished',
			'start_time' => $start_time,
			'end_time'   => $end_time,
		);
	
		$shop_info = Shop::shop_info($shop_id);
		$merchant_uid = Arr::get($shop_info,'uid',0);
		$bill['bill_list'] = $this->_bill->get_bill_list($condition,100000,0);
		$bill['profile']   = $this->_bill->get_profile_detail($shop_id,$month);
		$bill['ratio']     = $this->_ratio->merchant_ratio($merchant_uid);
		return $bill;
	}

	private function get_year_amount($year)
	{
		$start_time = strtotime($year.'-01-01 00:00:00');
		$end_time   = strtotime($year.'-12-31 23:59:59');
		$year_amount = $this->_bill->get_all_profile_amount($start_time,$end_time);
		return $year_amount;
	}

	private function get_amount($year)
	{
		$start_time = strtotime($year.'-01-01 00:00:00');
		$end_time   = strtotime($year.'-12-31 23:59:59');
		$condition  = array(
			'start_time'  => $start_time,
			'end_time'    => $end_time,
		);
		$profile_count = $this->_bill->get_profile_count($condition);
		$profile_list = $this->_bill->get_profile_list($condition,$profile_count);

		$result = array();
		$month_amount = array();
		$year_amount = array(
			'amount_real'    => 0,
			'amount_service' => 0,
		);

		foreach ($profile_list as $item)
		{
			if (!isset($month_amount[$item['month']]))
			{
				$month_amount[$item['month']]['real']    = $item['amount_real'];
				$month_amount[$item['month']]['service'] = $item['amount_service'];
			}
			else
			{
				$month_amount[$item['month']]['real']    += $item['amount_real'];
				$month_amount[$item['month']]['service'] += $item['amount_service'];
			}
			$year_amount['real'] += $item['amount_real'];
			$year_amount['service'] += $item['amount_service'];
		}
		$result = array(
			'month' => $month_amount,
			'year'  => $year_amount,
		);
		return $result;
	}
}
